import { Component, OnInit, ViewChild, OnDestroy, AfterContentInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { TitleService } from '@delon/theme';
import { Constant, ServiceResult } from '@core/constant';
import { ProductService } from '../../../../service/prod/product.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';

@Component({
  selector: 'product-view-edit',
  templateUrl: './product-edit.component.html',
  styleUrls: ['./product-edit.component.less']
})
export class ProductViewEditComponent implements OnInit, OnDestroy {
  product: {[propName: string]: any;} = {}
  // 预览图片地址
  picUrl = '';
  // 图片上传地址
  uploadUrl = ''; 
  seasons = [];
  categorys = [];
  brandLines = [];
  years = [];
  brands = [];
  userGroups = [];  
  isAds = [{ text: '广告款', value: this.cnt.BoolUtil.TRUE}, { text: '普通款', value: this.cnt.BoolUtil.FALSE }];
  isCms = [{ text: '是', value: this.cnt.BoolUtil.TRUE}, { text: '否', value: this.cnt.BoolUtil.FALSE }];

  MAX_COUNT = 60;
  tabIndex = 0;
  saleing = false;  
  private sub: any;
  
  constructor(
    private msg: NzMessageService,
    private modalService: NzModalService,
    private productService: ProductService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private cnt: Constant,
    private router: Router,
    private comm: CommService
  ) {}

  ngOnInit(): void {
    this.uploadUrl = this.productService.uploadUrl();
    this.loadBrandLines();
    this.loadCategorys();
    this.loadBrands();
    this.loadSeasons();
    this.loadUserGroup();
    this.loadYears();
    

    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      this.product.id = params["id"];  
      // 获取商品详情     
      this.getProductInfo();
    });
    // 隐藏reusetab
    setTimeout(() => {
        this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 100);    
    this.titleService.setTitle("编辑产品")    
  }

  // 显示reusetab
  ngOnDestroy() {    
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }

  changeTab(index) {
    // 使用异步的方式更新组件, 防止ngIf错误   
    Promise.resolve(null).then(() => this.tabIndex = index);
  }

  // 加载产品季节
  loadSeasons() {
    this.seasons = [];
    this.comm.getSeasons().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.seasons.push({ text: row.labelDefault, value: row.value });
          }                                   
      }
    })
  }

  // 加载品牌分类
  loadCategorys() {
    this.categorys = [];
    this.comm.getCategory().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.categorys.push({ text: row.labelDefault, value: row.value });
          }                                   
      }
    })
  }

  // 加载品项列表
  loadBrandLines() {
    this.brandLines = [];
    this.comm.getBrandLine().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.brandLines.push({ text: row.labelDefault, value: row.value });
          }                                   
      }
    })
  }


  loadYears() {
    this.years = [];
    this.comm.getYear().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
        for (const row of ret['data']['rows']) {
          this.years.push({ text: row.labelDefault, value: row.value });
        }                                   
      }
    })
  }

  // 加载品牌列表
  loadBrands() {
    this.brands = [];
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
        for (const row of ret['data']['rows']) {
          this.brands.push({ text: row.labelDefault, value: row.value });
        }                                   
      }
    })
  }

  loadUserGroup() {
    this.userGroups = [];
    this.comm.getUserGroup().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
        for (const row of ret['data']['rows']) {
          this.userGroups.push({ text: row.labelDefault, value: row.value });
          }                                   
      }
    })
  }

  getProductInfo() {
    this.productService.getProduct(this.product.id).pipe(
      catchError(err => {                             
        return of(err);
      })
    ).subscribe(data => {
      this.product = data.data;
      // 设置上下架状态
      this.saleing = this.product.status === this.cnt.BoolUtil.TRUE;            
      // 拼接图片地址
      this.picUrl = this.comm.getGoodsUrl() + this.product.img;        
    })
  }


  beforeUpload = (file: File) => {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      if (!isJPG && !isPNG) {
          this.msg.warning(`不支持的格式: ${file.type}`);            
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
          this.msg.warning('图片不能超过2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
  }

  private getBase64(img: File, callback: (img: any) => void) {
      if (img) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
      }
  }

  handleChange(row, col, info: { file: UploadFile }) {
      if (info.file.status === 'uploading') {            
          return;
      }
      if (info.file.status === 'done') {  
          let that = this;   
          let f = info;       
          this.getBase64(info.file.originFileObj, (img: any) => { 
            that.picUrl = img;
            that.product.img =  f.file.response.rows[0].id;              
          });
      }
      if (info.file.status === 'error') {
          this.msg.error(info.file.error.error);
      }
  }

  formatterYuan = value => `¥ ${value}`;
  parserYuan = value => value.replace('¥', '');

  formatterDollor = value => `${value}`;
  parserDollor = value => value.replace('$', '');

  back() {
    this.router.navigate(['/prod/product']);
  }
  

  save() {

    if (!this.product.brandLine) {         
      this.msg.warning("请选择品项");
      return;
    }

    if (!this.product.category) {         
      this.msg.warning("请选择分类");
      return;
    }

    if (!this.product.brand) {         
        this.msg.warning("请选择品牌");
        return;
    }    

    if (!this.product.year) {
        this.msg.warning("请选择年份");
        return;
    } 

    
    if (!this.product.season) {         
      this.msg.warning("请选择产品季");
      return;
    }

    if (!this.product.userGroup) {
        this.msg.warning("请选择款式");
        return;
    }

    

    this.product.isAd = this.product.isAd ? this.product.isAd : this.cnt.BoolUtil.FALSE;
    this.product.isCm = this.product.isCm ? this.product.isCm : this.cnt.BoolUtil.FALSE; 
    this.product.status =  this.saleing ? this.cnt.BoolUtil.TRUE : this.cnt.BoolUtil.FALSE;

   
    // 调用接口
    this.productService.editPro(this.product).pipe(
      catchError(err => {                             
        return of(err);
      })
    ).subscribe(data => {
      if (data.status === 200) {
        this.msg.success('修改成功');
        this.emit.sendMessage("RELOAD_GOODS_LIST");
      } else {
        this.msg.error(data['message']);
      }
    })
  }

  changeColor(res) {
    this.product.colorSort = res.color.hex;
  }
}
